<template>
  <div>
    <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="1"
        :labelWidth="110"
        formType="add"
        :isSubmitBtn="false"
        @formChange="changeHandle"
      />

      <BreakSpace label="角色维护" :containerStyle="{ marginBottom: '10px' }" />

      <FilterTable
      height="300"
      ref="oemRoleTable"
      :columns="oemRoleColumns"
      :dataSource="groupRoleList"
      :isSelectColumn="isSelectColumn"
      :datakey="'records'"
      :disabled="isOperator"
      :isToperInfo="false"
      :onColumnsChange="oemRoleColumns => (this.oemRoleColumns = oemRoleColumns)"
      columnsRef="notification_maintain_roleGroup_01"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="roleAdd" :disabled="isOperator">添加角色</el-button>
      </template>
    </FilterTable>

    <!-- 角色选择弹窗 -->
    <BaseDialog title="车厂角色选择" :visible.sync="visibleOemRole" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <oem-role ref="addOemRole" @close="closeOemRole" />
    </BaseDialog>

      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="saveDialog" type="primary" :loading="saveLoading">保 存</el-button>
      </div>

  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import oemRole from '@/pages/cms-pages/notification/maintain/oemRole';
import { addOemRoleGroup ,updateOemRoleGroup} from '@/api/cms-api/notification/maintain/index';

export default {
  mixins: [dictionary],
  components: {
    oemRole
  },
  props: {
    type: {
      type: String
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formList: this.createFormList(),
      oemRoleColumns: this.creatHeader4OemRoleColumns(),
      groupRoleList: [],
      isSelectColumn: false,
      isOperator:  false, // 是否是详情
      visibleOemRole: false,
      saveLoading:false,
      groupType:'',
      dataMain:null
    };
  },
  created() {
    this.init();
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '分组名称',
          fieldName: 'notificationGroupName',
          placeholder: '请输入...',
          maxlength:300,
          rules: [{ required: true,  trigger: 'blur',message: '请输入分组名称' }]
        }
      ]
    },
    // 车厂角色选择列表
    creatHeader4OemRoleColumns4disabled() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        { title: '角色代码', dataIndex: 'roleCode', sorter: true },
        { title: '角色名称', dataIndex: 'roleName', sorter: true }
      ];
    },
    // 车厂角色选择列表
    creatHeader4OemRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteoemRole(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '角色代码', dataIndex: 'roleCode', sorter: true },
        { title: '角色名称', dataIndex: 'roleName', sorter: true }
      ];
    },
    deleteoemRole(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.groupRoleList.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 角色选择窗口打开 -传数据
    roleAdd() {
      this.initDealerRoleData = {
        id: 1001
      }; //行id
      this.visibleOemRole = true;
    },
    // 角色选择窗口 -返回数据
    closeOemRole(data) {
      // this.groupRoleList = data.data;
      console.log('选择角色回来的数据',data)
      this.addSelectOemRole(data.data);
      this.visibleOemRole = data.visible; //关闭弹窗
    },
    //添加选择车角色到列表中
    addSelectOemRole(oemRoles) {
      if (oemRoles != null && typeof oemRoles != 'undefined' && oemRoles.length > 0) {
        oemRoles.forEach(oemRole => {
          let roleCode = oemRole.roleCode;
          if (!this.isExistInlistOemRole(roleCode)) {
            this.groupRoleList.push(oemRole);
          }
        });
        console.log('数据',this.groupRoleList)
        this.groupRoleList.dataMark = false;
      }
    },
    isExistInlistOemRole(roleCode) {
      let r = false;
      if (this.groupRoleList && this.groupRoleList.length > 0) {
        for (let dIdx = 0; dIdx < this.groupRoleList.length; dIdx++) {
          let tcode = this.groupRoleList[dIdx].roleCode;
          if (tcode === roleCode) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    //保存
    saveDialog() {
      this.groupType = '1';
      this.$refs.formPanel.SUBMIT_FORM();
    },
    changeHandle(data) {
      this.dataMain = data;
      this.submit();
    },
    // 保存
    async submit() {
      var flag = this.packageData();
      if (flag === -1) {
        return;
      }
      this.saveLoading = true;
      console.log(this.dataMain)
      if(this.type == 'edit'){
        this.dataMain.notificationGroupId = this.rowData.notificationGroupId;
        console.log('修改参数',this.dataMain)
        this.validReturnDate(await updateOemRoleGroup(this.dataMain));
      }else{
        this.validReturnDate(await addOemRoleGroup(this.dataMain));
      }
    },
    validReturnDate(res) {
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
      }
    },
    // 数据组装
    packageData() {
      this.packageListOemRole();
      this.dataMain.notificationGroupType = this.groupType;
    },
    // 封装车厂角色信息
    packageListOemRole() {
      console.log('走你',this.groupRoleList)
      if (this.groupRoleList == null) {
        this.dataMain.groupRoleList = [];
        return;
      }
      let temp = [];
      for (let i = 0; i < this.groupRoleList.length; i++) {
        let body = {};
        body.roleCode = this.groupRoleList[i].roleCode;
        body.roleId = this.groupRoleList[i].roleId;
        body.roleName = this.groupRoleList[i].roleName;
        body.type = 1;
        temp.push(body);
      }
      this.dataMain.groupRoleList = temp;
    },
    closeDialog(type) {
      this.$emit('close', false, type);
    },
    init() {
      if (this.type === 'edit') {
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });

      let rows = [];
      if(this.rowData.roleId != null){
        if (this.rowData.roleId.indexOf(',')  != -1) {
          let roleIds = this.rowData.roleId.split(',');
          let roleCodes = this.rowData.roleCode.split(',');
          let roleNames = this.rowData.roleName.split(',');
          for (let y = 0 ;y < roleIds.length ; y++) {
              let data = {}
              data.roleId = parseInt(roleIds[y]);
              data.roleCode  =  roleCodes[y];
              data.roleName  =  roleNames[y];
              rows.push(data);
          }
        }else{
          let data2 = {}
          data2.roleId = parseInt(this.rowData.roleId);
          data2.roleCode  =  this.rowData.roleCode;
          data2.roleName  =  this.rowData.roleName;
          rows.push(data2);
        }
      }
      this.addSelectOemRole(rows);
       }
    },
  }
};
</script>

<style lang="less" scoped>
</style>
